import { useSettingsStore } from '../stores/settings';
import request from '@/utils/request';
import axios from 'axios';
import { handleTokenExpired, refreshAccessToken } from '@/utils/request';
import { ElMessage } from 'element-plus';


import { useUserStore } from '@/stores/user'; // 导入用户 Store

const createHeaders = () => {
  const userStore = useUserStore(); // 获取用户 Store
  const token = userStore.token; // 从用户信息中获取 token
  return {
    'Authorization': token,
  };
};


export const chatApi = {
  async sendMessage(payload, stream = false) {
    const settingsStore = useSettingsStore();
    const Type = settingsStore.model.type;
    const API_URL = settingsStore.model.value;
    const apiPath = Type === 'kingsha' ? '/external/ai' : '/external/ai';

    try {
      if (stream) {
        const response = await fetch(
          `${API_URL}${apiPath}`,
          {
            method: 'POST',
            headers: {
              ...createHeaders(),
              'Accept': 'text/event-stream'
            },
            body: payload
          }
        );

        if (!response.ok) {
          throw new Error(`HTTP 错误: ${response.status}`);
        }

        // 预读首包数据检查状态码（但不消耗流）
        const reader = response.body.getReader();
        const { value: firstChunk, done } = await reader.read();
        let initialChunk = '';
        if (!done && firstChunk) { // 修正此处的变量名引用
          initialChunk = new TextDecoder().decode(firstChunk);
        }

        // 检查状态码
        const validData = await this.checkStreamStatus(initialChunk);
        if (!validData) {
          // Token 过期，刷新后重试
          await handleTokenExpired();
          return await this.sendMessage(payload, stream);
        } else if (validData?.status !== 200) {
          throw new Error(validData.message || '业务状态码错误');
        }

        // 创建新的可读流，包含预读数据和剩余数据
        const remainingStream = new ReadableStream({
          start(controller) {
            // 将预读的首包数据作为第一个块发送
            controller.enqueue(firstChunk);

            // 递归读取剩余数据
            const pump = (reader) => {
              return reader.read().then(({ value, done }) => {
                if (done) {
                  controller.close();
                  return;
                }
                controller.enqueue(value);
                return pump(reader);
              });
            };
            pump(reader); // 使用原始 reader 处理剩余数据
          }
        });

        // 返回包含完整流的响应对象
        return {
          body: remainingStream
        };
      } else {
        const response = await request.post(
          `${API_URL}${apiPath}`,
          payload,
          {
            headers: createHeaders()
          }
        );
        return response.data;
      }
    } catch (error) {
      if (error.response) {
        const { status, data } = error.response;
        const errorMessage = data?.message || `HTTP ${status} 错误`;
        ElMessage.error(errorMessage);
      } else {
        ElMessage.error(error.message);
      }
      throw error;
    }
  },

  // 新增方法：解析预读数据的状态码
  async checkStreamStatus(initialChunk) {
    let validData = null;
    if (initialChunk) {
      const lines = initialChunk.split('\n');
      for (const line of lines) {
        if (line.startsWith('data: ')) {
          const jsonStr = line.slice(6);
          try {
            validData = JSON.parse(jsonStr);
          } catch (e) {
            console.error('JSON解析失败:', e);
          }
        }
      }
    }
    return validData;
  }
};